import router from '@/router'
import store from '@/store'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { cancelAll } from '@/utils/request.js'

const whitePath = ['/404', '/login']

router.beforeEach(async(to, from, next) => {
  cancelAll() // 取消跳转前页面的所有请求
  Nprogress.start()
  if (store.getters.token) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      if (!store.state.user.profile.userId) {
        await store.dispatch('user/getProfile')
        next(to.fullPath)
      } else {
        next()
      }
    }
  } else {
    if (whitePath.includes(to.path.toLowerCase())) {
      next()
    } else {
      next('/login?redirect=' + to.fullPath)
    }
  }
  Nprogress.done()
})

router.afterEach((to, from) => {
  Nprogress.done()
})
